package com.ruoyi.web.controller.shopping;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.ruoyi.common.core.controller.HandleVideoSrc;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shopping.domain.*;
import com.ruoyi.shopping.service.*;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.poi.hssf.record.PageBreakRecord;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商城商品Controller
 *
 * @author ruoyi
 * @date 2022-06-09
 */
@RestController
@RequestMapping("/shopping/mallProduct")
public class MallProductController extends BaseController
{
    @Autowired
    private IMallProductService mallProductService;
    @Autowired
    private IMallClassifyService mallClassifyService;
    @Autowired
    private IMallProductSpecsService mallProductSpecsService;
    @Autowired
    private IMallProductBackService mallProductBackService;
    @Autowired
    private IMallProductSpecsBackService mallProductSpecsBackService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 修改商品上下架状态
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallProduct:edit')")
    @PutMapping("/editStatus")
    public AjaxResult editStatus(String status,Long id ) {
        MallProduct mallProduct = new MallProduct();
        mallProduct.setId(id);
        mallProduct.setIsShow(status);
        mallProductService.updateMallProduct(mallProduct);


        return AjaxResult.success();

    }
    /**
     * 商城订单获取商品信息
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallProduct:query')")
    @GetMapping("/getProduct")
    public AjaxResult getProduct( Long id) {
        MallProduct mallProduct = mallProductService.selectMallProductById(id);
        return AjaxResult.success(mallProduct);
    }

//    /**
//     * 根据分类id查询商品
//     */
//    @GetMapping("/goodName")
//    public TableDataInfo getProductByClassify( MallProduct mallProduct)
//    {
//        startPage();
//        mallProduct.setIsShow("Y");
//        if (!StringUtils.isEmpty(mallProduct.getClassifyCodingName())){
//            String[] result = mallProduct.getClassifyCodingName().split(",");
//            if (result.length!=1){
//                String twoClassify = mallProduct.getClassifyCodingName().split(",")[1];
//                mallProduct.setClassifyId(Long.valueOf(twoClassify));
//            }
//        }
//        List<MallProduct> mallProducts = mallProductService.selectMallProductList(mallProduct);
//        return getDataTable(mallProducts);
//    }

    /**
     * 查询商城商品列表
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallProduct:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallProduct mallProduct)
    {
        startPage();
        if (!StringUtils.isEmpty(mallProduct.getClassifyCodingName())){
            String[] result = mallProduct.getClassifyCodingName().split(",");
            if (result.length!=1){
            String twoClassify = mallProduct.getClassifyCodingName().split(",")[1];
            mallProduct.setClassifyId(Long.valueOf(twoClassify));
        }
        }
        List<MallProduct> list = mallProductService.selectMallProductList(mallProduct);
        return getDataTable(list);
    }



    /**
     * 导出商城商品列表
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallProduct:export')")
    @Log(title = "商城商品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MallProduct mallProduct)
    {
        List<MallProduct> list = mallProductService.selectMallProductList(mallProduct);
        ExcelUtil<MallProduct> util = new ExcelUtil<MallProduct>(MallProduct.class);
        return util.exportExcel(list, "商城商品数据");
    }

    /**
     * 获取商城商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallProduct:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {

        MallProduct product = mallProductService.selectMallProductById(id);
        //商品分类对象 mallClassify
        MallClassify mallClassify = mallClassifyService.selectMallClassifyById(product.getClassifyId());
        Long parentId = mallClassify.getParentId();
        product.setClassifyCodingName(parentId.longValue()+","+mallClassify.getId().longValue());
        return AjaxResult.success(product);
    }

    /**
     * 新增商城商品
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallProduct:add')")
    @Log(title = "商城商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallProduct mallProduct)
    {
        //商品分类不能为空
        if (null == mallProduct.getClassifyCodingName()){
            return AjaxResult.error("商品分类不能为空");
        }
        String[] result = mallProduct.getClassifyCodingName().split(",");
        if (result.length==1){
            return AjaxResult.error("商品必须选择二级分类，请联系管理员");
        }
        String oneClassify = result[0];
        String twoClassify = result[1];
        mallProduct.setClassifyId(Long.parseLong(twoClassify));//只存最后一级的id
        MallClassify mallClassify1 = mallClassifyService.selectMallClassifyById(Long.parseLong(oneClassify));//一级
        MallClassify mallClassify = mallClassifyService.selectMallClassifyById(Long.parseLong(twoClassify));//二级
        String str = mallClassify1.getClassifyName()+","+mallClassify.getClassifyName();//分类名称
        mallProduct.setClassifyName(str);
        if(StringUtils.isNotEmpty(mallProduct.getProductMainVideo())){
            Map<String, String> val = configService.getVal();
            mallProduct.setVideoCover(HandleVideoSrc.handle(val.get("key"),val.get("id"),val.get("region"),val.get("bn"),mallProduct.getProductMainVideo()));
        }
        String richText=mallProduct.getRichText();
        if(!StringUtils.isEmpty(richText)){
            richText=richText.replaceAll("<img src=","<img style='display: block;max-width:100%;height:auto;' src=");
        }
        mallProduct.setRichText(richText);

        mallProductService.insertMallProduct(mallProduct);
        //新增的时候把新增的信息传给商品快照
        MallProductBack mallProductBack = new MallProductBack();
        mallProductBack.setProductId(mallProduct.getId());//商品id
        mallProductBack.setProductName(mallProduct.getProductName());//商品名称
        mallProductBack.setProductImage(mallProduct.getProductImage());//商品主图
        mallProductBack.setProductDeputyImage(mallProduct.getProductDeputyImage());//商品副图


        mallProductBack.setRichText(mallProduct.getRichText());//商品详情
        mallProductBack.setClassifyId(mallProduct.getClassifyId());//分类id
        mallProductBack.setClassifyName(mallProduct.getClassifyName());//分类名称
        mallProductBack.setSort(mallProduct.getSort());//排序
        mallProductBack.setService(mallProduct.getService());//提供服务
        mallProductBack.setWhetherSelling(mallProduct.getWhetherSelling());//是否热卖
        mallProductBack.setProductMainVideo(mallProduct.getProductMainVideo());//商品主视图
        mallProductBackService.insertMallProductBack(mallProductBack);
        //新增后的快照信息把id传给商品表的快照id



        MallProduct mallProduct1 = new MallProduct();
        mallProduct1.setId(mallProduct.getId());
        mallProduct1.setProductBackId(mallProductBack.getId());
        mallProductService.updateMallProduct(mallProduct1);
       /* List<MallProduct> mallProducts = mallProductService.selectMallProductList(mallProduct1);
        for (MallProduct product : mallProducts) {
            product.setProductBackId(mallProductBack.getId());
            mallProductService.updateMallProduct(product);
        }*/
        //前端传回来的规格信息（DataValue）是数组形式需要转换称对象
        List<MallProductSpecs> list = mallProduct.getDataValue();
        for (MallProductSpecs productSpecs : list) {
            //新增后取商品主键赋值给商品规格中的商品id
            productSpecs.setProductId(mallProduct.getId());
            mallProductSpecsService.insertMallProductSpecs(productSpecs);
            //规格新增后将信息备份到商品规格快照中
            MallProductSpecsBack mallProductSpecsBack = new MallProductSpecsBack();
            mallProductSpecsBack.setProductBackId(mallProductBack.getId());//商品备份id
            mallProductSpecsBack.setSpecsId(productSpecs.getId());//规格id
            mallProductSpecsBack.setSpecsName(productSpecs.getSpecsName());//规格名称
            mallProductSpecsBack.setSpecsPhoto(productSpecs.getSpecsPhoto());
            mallProductSpecsBack.setSort(productSpecs.getSort());
            mallProductSpecsBack.setOriginalPrice(productSpecs.getOriginalPrice());
            mallProductSpecsBack.setCurrentPrice(productSpecs.getCurrentPrice());
            mallProductSpecsBack.setSalesNum(productSpecs.getSalesNum());
            mallProductSpecsBackService.insertMallProductSpecsBack(mallProductSpecsBack);
            //新增到规格快照的id返回给规格表
            MallProductSpecs mallProductSpecsBackId = new MallProductSpecs();
            mallProductSpecsBackId.setId(mallProductSpecsBack.getSpecsId());
            mallProductSpecsBackId.setSpecsBackId(mallProductSpecsBack.getId());
            mallProductSpecsService.updateMallProductSpecs(mallProductSpecsBackId);

        }


        //规格新增后原价，售价，销量作比较赋值给商品的原价售价，销量
        MallProductSpecs mallProductSpecs = new MallProductSpecs();
        mallProductSpecs.setProductId(mallProduct.getId());
        List<MallProductSpecs> mallProductSpecs1 = mallProductSpecsService.selectMallProductSpecsList(mallProductSpecs);
        MallProductSpecs mallProductSpecs2 = mallProductSpecs1.stream().min(Comparator.comparing(MallProductSpecs::getCurrentPrice)).get();
        //获取商品规格销量的总和
        Integer collect = mallProductSpecs1.stream().collect(Collectors.summingInt(MallProductSpecs::getSalesNum));
        mallProduct.setCurrentPrice(mallProductSpecs2.getCurrentPrice());
        mallProduct.setOldPrice(mallProductSpecs2.getOriginalPrice());
        mallProduct.setSalesNum(collect);
        mallProductService.updateMallProduct(mallProduct);

        return AjaxResult.success();
    }


    /**
     * 修改商城商品
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallProduct:edit')")
    @Log(title = "商城商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallProduct mallProduct)
    {
        mallProduct.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        String CodingName = mallProduct.getClassifyCodingName();
        if (!StringUtils.isEmpty(CodingName)){
            String[] result = mallProduct.getClassifyCodingName().split(",");
            String oneClassify = result[0];
            String twoClassify = result[1];
            mallProduct.setClassifyId(Long.parseLong(twoClassify));//只存最后一级的id
            MallClassify mallClassify1 = mallClassifyService.selectMallClassifyById(Long.parseLong(oneClassify));//一级
            MallClassify mallClassify = mallClassifyService.selectMallClassifyById(Long.parseLong(twoClassify));//二级
            String str = mallClassify1.getClassifyName()+","+mallClassify.getClassifyName();//分类名称
            mallProduct.setClassifyName(str);
        }
        String richText=mallProduct.getRichText();
        if(!StringUtils.isEmpty(richText)){
            richText=richText.replaceAll("<img src=","<img style='display: block;max-width:100%;height:auto;' src=");
        }
        if(StringUtils.isNotEmpty(mallProduct.getProductMainVideo())){
            Map<String, String> val = configService.getVal();
            mallProduct.setVideoCover(HandleVideoSrc.handle(val.get("key"),val.get("id"),val.get("region"),val.get("bn"),mallProduct.getProductMainVideo()));
        }
        if(StringUtils.isNotEmpty(mallProduct.getProductMainVideo())){
            Map<String, String> val = configService.getVal();
            mallProduct.setVideoCover(HandleVideoSrc.handle(val.get("key"),val.get("id"),val.get("region"),val.get("bn"),mallProduct.getProductMainVideo()));
        }
        mallProduct.setRichText(richText);

        //新增快照
        MallProductBack mallProductBack = new MallProductBack();
        mallProductBack.setProductId(mallProduct.getId());
        mallProductBack.setProductName(mallProduct.getProductName());
        mallProductBack.setProductMainVideo(mallProduct.getProductMainVideo());
        mallProductBack.setVideoCover(mallProduct.getVideoCover());
        mallProductBack.setVideoCover(mallProduct.getVideoCover());

        mallProductBack.setProductImage(mallProduct.getProductImage());
        mallProductBack.setProductDeputyImage(mallProduct.getProductDeputyImage());
        mallProductBack .setRichText(mallProduct.getRichText());
        mallProductBack.setClassifyId(mallProduct.getClassifyId());
        mallProductBack.setSort(mallProduct.getSort());
        mallProductBack.setClassifyName(mallProduct.getClassifyName());
        mallProductBack.setService(mallProduct.getService());
        mallProductBackService.insertMallProductBack(mallProductBack);
        mallProduct.setProductBackId(mallProductBack.getId());
        //商品规格的修改
        //修改同时向快照表中添加信息
        //在修改中删除规格

        List<MallProductSpecs> list = mallProduct.getDataValue();
        Map<Long,MallProductSpecs> mapPage=list.stream().collect(Collectors.toMap(MallProductSpecs::getId, Function.identity()));
        MallProductSpecs mallProductSpecs = new MallProductSpecs();
        mallProductSpecs.setProductId(mallProduct.getId());
        List<MallProductSpecs> getAll = mallProductSpecsService.selectMallProductSpecsList(mallProductSpecs);//数据库查到所有的
        List<Long> delIds=new ArrayList<Long>();
        for (MallProductSpecs mps:getAll){
            if(!mapPage.containsKey(mps.getId())){
                delIds.add(mps.getId());
            }
        }
        if(delIds.size()>0){
            mallProductSpecsService.logicDeleteMallProductSpecs(delIds.toArray(new Long[delIds.size()]),DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId());
        }


//       修改中添加规格
        for (MallProductSpecs productSpecs : list) {
//            修改中新增一条商品规格信息，首先判断通过id查询的数据是否含有商品id 如果没有ProductId
//            说明是修改操作中新增的信息然后执行新增操作，并且赋值对应的商品id
            if (null == productSpecs.getProductId()){
                productSpecs.setProductId(mallProduct.getId());
                mallProductSpecsService.insertMallProductSpecs(productSpecs);

                //规格新增后将信息备份到商品规格快照中
                MallProductSpecsBack mallProductSpecsBack = new MallProductSpecsBack();
                mallProductSpecsBack.setProductBackId(productSpecs.getId());//商品备份id
                mallProductSpecsBack.setSpecsId(productSpecs.getId());//规格id
                mallProductSpecsBack.setSpecsName(productSpecs.getSpecsName());//规格名称
                mallProductSpecsBack.setSpecsPhoto(productSpecs.getSpecsPhoto());
                mallProductSpecsBack.setSort(productSpecs.getSort());
                mallProductSpecsBack.setOriginalPrice(productSpecs.getOriginalPrice());
                mallProductSpecsBack.setCurrentPrice(productSpecs.getCurrentPrice());
                mallProductSpecsBack.setSalesNum(productSpecs.getSalesNum());
                mallProductSpecsBackService.insertMallProductSpecsBack(mallProductSpecsBack);
                //将快照id返回给规格中的快照id
                MallProductSpecs mallProductSpecs1 = new MallProductSpecs();
                mallProductSpecs1.setId(mallProductSpecsBack.getSpecsId());
                mallProductSpecs1.setSpecsBackId(mallProductSpecsBack.getId());
                mallProductSpecsService.updateMallProductSpecs(mallProductSpecs1);


            }else{

                //修改中修改规格
                mallProductSpecsService.updateMallProductSpecs(productSpecs);
                MallProductSpecsBack mallProductSpecsBack = new MallProductSpecsBack();
                mallProductSpecsBack.setProductBackId(mallProductBack.getId());//商品备份id
                //规格新增后将信息备份到商品规格快照中
                mallProductSpecsBack.setSpecsId(productSpecs.getId());//规格id
                mallProductSpecsBack.setSpecsName(productSpecs.getSpecsName());//规格名称
                mallProductSpecsBack.setSpecsPhoto(productSpecs.getSpecsPhoto());
                mallProductSpecsBack.setSort(productSpecs.getSort());
                mallProductSpecsBack.setOriginalPrice(productSpecs.getOriginalPrice());
                mallProductSpecsBack.setCurrentPrice(productSpecs.getCurrentPrice());
                mallProductSpecsBack.setSalesNum(productSpecs.getSalesNum());
                mallProductSpecsBackService.insertMallProductSpecsBack(mallProductSpecsBack);
                //将快照id返回给规格中的快照id
                MallProductSpecs mallProductSpecs1 = new MallProductSpecs();
                mallProductSpecs1.setId(mallProductSpecsBack.getSpecsId());
                mallProductSpecs1.setSpecsBackId(mallProductSpecsBack.getId());
                mallProductSpecsService.updateMallProductSpecs(mallProductSpecs1);
            }
        }
        //规格新增后原价售价销量做处理给商品表的原价售价销量（条件，现价取最小值的售价和所有对应的规格数量之和）
        MallProductSpecs getAllProductSpecs = new MallProductSpecs();//先查询出来所有对应商品id的规格
        getAllProductSpecs.setDelState(DicConstants.SYS_N.getCode());
        getAllProductSpecs.setProductId(mallProduct.getId());
        List<MallProductSpecs> getAllProductSpecsList = mallProductSpecsService.selectMallProductSpecsList(getAllProductSpecs);
        //获取商品规格中最低的现价和对应的原价
        MallProductSpecs getMinCurrentPrice = getAllProductSpecsList.stream().min(Comparator.comparing(MallProductSpecs::getCurrentPrice)).get();
        //获取商品规格销量的总和
        Integer collect = getAllProductSpecsList.stream().collect(Collectors.summingInt(MallProductSpecs::getSalesNum));
        mallProduct.setCurrentPrice(getMinCurrentPrice.getCurrentPrice());
        mallProduct.setOldPrice(getMinCurrentPrice.getOriginalPrice());
        mallProduct.setSalesNum(collect);
        mallProductService.updateMallProduct(mallProduct);

        return AjaxResult.success();
    }

    /**
     * 删除商城商品
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallProduct:remove')")
    @Log(title = "商城商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mallProductService.logicDeleteMallProduct(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }
}
